import React, { Component, createRef } from "react";
import { Card, Button, Table, Modal, message } from "antd";
import { PAGE_SIZE } from "../../utils/constants";
import AddForm from "./add-form";
import AuthForm  from './update-form'
import { reqAddRole, reqRoles, reqUpdateRole } from "../../api";
import { formateDate} from '../../utils/dateUtils'
import memoryUtils from "../../utils/memoryUtils";
import storageUtils from '../../utils/storageUtils'


class role extends Component {
  formRef = React.createRef();
  authRef = React.createRef()
  state = {
    roles: [],
    role: {},
    isShowAdd: false,
    isShowAuth:false
  };
  initColumn = () => {
    this.columns = [
      {
        title: "角色名称",
        dataIndex: "name",
      },
      {
        title: "创建时间",
        dataIndex: "create_time",
        render:formateDate
      },
      {
        title: "授权时间",
        dataIndex: "auth_time",
        render:formateDate
      },
      {
        title: "授权人",
        dataIndex: "auth_name",
        
      },
    ];
  };
  addRole = () => {
    //收集输入数据
    this.formRef.current.formRef.current
      .validateFields()
      .then(async (values) => {
        const { role } = values;
        const res = await reqAddRole(role);

        if (res.data.status === 0) {
          message.success("添加角色成功");
          this.getRoles();
        } else {
          message.error("添加角色失败");
        }
      });
    this.setState({ isShowAdd: false });
  };
  updateRole = async() => { 
    const role = this.state.role
    console.log(this.authRef.current.getMenus());
    const menus = this.authRef.current.getMenus()
    role.menus = menus
    const res = await reqUpdateRole( role )
    if ( res.data.status === 0 ) { 
		message.success( '设置角色权限成功' )
		
		if (role._id===memoryUtils.user.role._id) {
			memoryUtils.user = {}
			storageUtils.removeUser()
			this.props.history.replace('/login')
		} else { 
			this.getRoles()
		}
      
      this.setState({isShowAuth:false})
    } else {
      message.error('设置角色权限失败')
    }
    
  }
  getRoles = async () => {
    const res = await reqRoles();
    console.log(res);
    if (res.data.status === 0) {
      const roles = res.data.data;
      this.setState({ roles });
    }
  };
  componentWillMount() {
    this.initColumn();
  }
  componentDidMount() {
    this.getRoles();
  }
  onRow = (role) => {
    return {
      onClick: (event) => {
        console.log(role);
        this.setState({ role });
      },
    };
  };

  render() {
    const { roles, isShowAdd, role ,isShowAuth} = this.state;
    const title = (
      <span>
        <Button
          type="primary"
          onClick={() => this.setState({ isShowAdd: true })}
        >
          创建角色
        </Button>
        &nbsp;&nbsp;
        <Button type="primary" onClick={ () => this.setState( {isShowAuth:true})} disabled={!role._id}>
          设置角色权限
        </Button>
      </span>
    );
    return (
      <Card title={title}>
        <Table
          bordered
          rowKey="_id"
          pagination={{ defaultPageSize: PAGE_SIZE, showQuickJumper: true }}
          rowSelection={{ type: "radio", selectedRowKeys: [role._id] }}
          onRow={this.onRow}
          dataSource={roles}
          columns={this.columns}
        ></Table>
        <Modal
          title="添加角色"
          visible={isShowAdd}
          onOk={this.addRole}
          onCancel={() => {
            this.setState({ isShowAdd: false });
          }}
        >
          <AddForm ref={this.formRef} />
        </Modal>
        <Modal
          title="设置角色权限"
          visible={isShowAuth}
          onOk={this.updateRole}
          onCancel={() => {
            this.setState({ isShowAuth: false });
          }}
        >
          <AuthForm key={ role._id} ref={this.authRef} role={ role} />
        </Modal>
      </Card>
    );
  }
}

export default role;
